import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        combinationSumHelper(candidates, target, 0, 0);
        return result;
    }
    private void combinationSumHelper(int[] candidates, int target, int startIndex, int sum){

        if(sum == target){
            result.add(new ArrayList<>(path));
            return;
        }
        for(int i = startIndex; i < candidates.length; i++){
            // 剪枝
            if (sum + candidates[i] > target) {
                break;
            }
            //去重
            if (i > startIndex && candidates[i] == candidates[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            combinationSumHelper(candidates, target, i + 1, sum + candidates[i]);
            path.remove(path.size() - 1);
        }

    }

}
